package com.bhkj.pdjhforotherapp;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;

import com.bhkj.pdjhforotherapp.common.bean.JhAudioBean;
import com.blankj.utilcode.util.GsonUtils;
import com.mine.vioceplaylib.sound.SoundPlayUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity {
    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
//
//        LemonHello.getSuccessHello("取号成功\n" + "您的排队号码:" + 10001 + "\n请您到" + 1 + "号窗口排队等候", "")
//                .addAction(new LemonHelloAction(getString(R.string.close), (lemonHelloView, lemonHelloInfo, lemonHelloAction) -> {
//                    lemonHelloView.hide();
//                    finish();
//                })).show(this);

        //实例化SoundPool
//        AudioUtils.changeToReceiver(this);
    }

    //        List<String> datas = new ArrayList<>();
//        datas.add("0");
//        datas.add("0");
//        datas.add("1");
//        datas.add("2");
//        VoiceBuilder voiceBuilder = new VoiceBuilder.Builder()
//                .setPlease("请")
//                .setPrefixNum(datas)
//                .setNumStr("号")
//                .setToStr("到")
//                .setSubfixNum("1")
//                .setLast("号，窗口办理业务")
//                .builder();
//        VoicePlay.with(this)
//                .play(voiceBuilder);
    public void onPlay(View view) {
        List<Integer> prefixDatas = new ArrayList<>();
        List<Integer> subfixDatas = new ArrayList<>();
        prefixDatas.add(R.raw.t_0);
        prefixDatas.add(R.raw.t_0);
        prefixDatas.add(R.raw.t_1);
        prefixDatas.add(R.raw.t_2);

        subfixDatas.add(R.raw.t_1);


        String res = "{\"code\":200,\"datas\":[{\"takenum\":\"0091\",\"windownum\":\"10\"}," +
                "{\"takenum\":\"0032\",\"windownum\":\"12\"}," +
                "{\"takenum\":\"0006\",\"windownum\":\"16\"}," +
                "{\"takenum\":\"0009\",\"windownum\":\"5\"}]}";

        JhAudioBean jhAudioBean = GsonUtils.getGson().fromJson(res, JhAudioBean.class);
        if (jhAudioBean.isSuccess()) {


            for (JhAudioBean.DatasBean param : jhAudioBean.getDatas()) {
//                VoiceBuilder builder = new VoiceBuilder.Builder()
//                        .setPlease("pl")
//                        .setPrefixNum(str2Array(param.getTakenum()))
//                        .setSubfixNum("num")
//                        .setSubfixNum("to")
//                        .setPrefixNum(str2Array(param.getWindownum()))
//                        .setLast("last")
//                        .builder();
//                VoicePlay.with(this).play(builder);
//                SoundManager.getInstance().loadSoundWithCache(Tools.getApplicationByReflect(),param.getTakenum(),param.getWindownum());
                SoundPlayUtils.newInstance().playJhSound(param.getTakenum(), param.getWindownum(),null);
            }
        }
//        SoundManager.getInstance().loadSoundWithCache(this, "0123", "10");

    }

    private List<String> str2Array(String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }

        char[] charsMine = str.toCharArray();
        List<String> integers = new ArrayList<>();

        for (char param : charsMine) {
            switch (String.valueOf(param)) {
                case "0":
                    integers.add("t_0");
                    break;
                case "1":
                    integers.add("t_1");
                    break;
                case "2":
                    integers.add("t_2");
                    break;
                case "3":
                    integers.add("t_3");
                    break;
                case "4":
                    integers.add("t_4");
                    break;
                case "5":
                    integers.add("t_5");
                    break;
                case "6":
                    integers.add("t_6");
                    break;
                case "7":
                    integers.add("t_7");
                    break;
                case "8":
                    integers.add("t_8");
                    break;
                case "9":
                    integers.add("t_9");
                    break;
                case "A":
                case "a":
                    integers.add("t_a");
                    break;
                case "B":
                case "b":
                    integers.add("t_b");
                    break;
                case "C":
                case "c":
                    integers.add("t_c");
                    break;
                case "D":
                case "d":
                    integers.add("t_d");
                    break;
                case "E":
                case "e":
                    integers.add("t_e");
                    break;
                case "F":
                case "f":
                    integers.add("t_f");
                    break;
                case "G":
                case "g":
                    integers.add("t_g");
                    break;
                case "H":
                case "h":
                    integers.add("t_h");
                    break;
                case "I":
                case "i":
                    integers.add("t_i");
                    break;
                case "J":
                case "j":
                    integers.add("t_j");
                case "K":
                case "k":
                    integers.add("t_k");
                    break;
                case "L":
                case "l":
                    integers.add("t_l");
                    break;
                case "M":
                case "m":
                    integers.add("t_m");
                    break;
                case "N":
                case "n":
                    integers.add("t_n");
                    break;
                case "O":
                case "o":
                    integers.add("t_o");
                    break;
                case "Q":
                case "q":
                    integers.add("t_q");
                    break;
                case "R":
                case "r":
                    integers.add("t_r");
                    break;
                case "S":
                case "s":
                    integers.add("t_s");
                    break;
                case "T":
                case "t":
                    integers.add("t_t");
                    break;
                case "U":
                case "u":
                    integers.add("t_u");
                    break;
                case "V":
                case "v":
                    integers.add("t_v");
                    break;
                case "W":
                case "w":
                    integers.add("t_w");
                    break;
                case "X":
                case "x":
                    integers.add("t_x");
                    break;
                case "Y":
                case "y":
                    integers.add("t_y");
                    break;
                case "Z":
                case "z":
                    integers.add("t_z");
                    break;
                default:
                    break;
            }
        }

        return integers;
    }

    int counts = 0;

    private void loadSound(List<Integer> datas) {
        //声音ID 加载音频资源,这里用的是第二种，第三个参数为priority，声音的优先级*API中指出，priority参数目前没有效果，建议设置为1。

        final int voiceId = soundPool.load(this, datas.get(counts), 1);
        final int voiceDuration = getMp3Duration(this, datas.get(counts));
        //第一个参数soundID
        //第二个参数leftVolume为左侧音量值（范围= 0.0到1.0）
        //第三个参数rightVolume为右的音量值（范围= 0.0到1.0）
        //第四个参数priority 为流的优先级，值越大优先级高，影响当同时播放数量超出了最大支持数时SoundPool对该流的处理
        //第五个参数loop 为音频重复播放次数，0为值播放一次，-1为无限循环，其他值为播放loop+1次
        //第六个参数 rate为播放的速率，范围0.5-2.0(0.5为一半速率，1.0为正常速率，2.0为两倍速率)
        //异步需要等待加载完成，音频才能播放成功
        soundPool.setOnLoadCompleteListener((soundPool1, sampleId, status) -> {
            if (status == 0) {
                soundPool1.play(voiceId, 1, 1, 0, 0, 1);
                try {
                    if (counts == 0) {
                        Thread.sleep(voiceDuration - 300);
                    } else if (counts == 4) {
                        Thread.sleep(voiceDuration - 400);
                    } else if (counts == 5) {
                        Thread.sleep(voiceDuration - 500);
                    } else {
                        Thread.sleep(voiceDuration - 780);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counts++;
                if (counts < datas.size()) {
                    loadSound(datas);
                } else {
                    counts = 0;
                }
            }
        });
    }


    /**
     * 获取音频文件的时长
     */
    private int getMp3Duration(Context context, int rawId) {
        try {
            Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + rawId);
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(context, uri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepare();
            return mediaPlayer.getDuration();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
